// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import {isWeiXin,encodeUnicode} from './util/util.js'
// 引入路由 其实就是router文件夹下的index.js配置好的路由表
import router from './router'
// 引入Vuex的store对象
import store from './store'

// 引入VueLazyload插件
import VueLazyload from 'vue-lazyload'
// 将一张loading图片加载进来
import loading from './common/imgs/loading.gif'

// 引入fastclick并绑定到body 解决移动端点击响应延迟0.3s的问题
import FastClick from 'fastclick'
import './filters'
// 加载mockServer
import './mock/mockServer.js'
// 注冊全局组件标签
import {Button, Toast} from 'mint-ui'
// 注册长按指令
import LongTouch from './util/longTouch'
Vue.directive('LongTouch', LongTouch);
// 引入公共css文件
import '../static/css/reset.css';
import '../static/css/animate.css';
import '../static/css/config.css';
// import '../static/css/iconFont.css';
import '../static/js/webuploader-0.1.5/webuploader.css';
// 引入公共js文件

Vue.component(Button.name, Button) // <mt-button>

FastClick.attach(document.body)
Vue.config.productionTip = false
import vuePicturePreview from 'vue-picture-preview'
Vue.use(vuePicturePreview)

Vue.use(VueLazyload, { // 内部自定义一个指令lazy
  loading
})
/* eslint-disable no-new */

router.beforeEach(async (to, from, next)=>{
  if(to.meta.disCheck) {
  	next();
  	return;
  };
  console.log('to', to)
  await store.dispatch("saveCurUrl", {data: to}); //保存现有的url,等登录的时候进行跳转
	const l = JSON.parse(localStorage.getItem("loginInfo"));
  console.log('如果不是登录页面则保存历史记录', to.fullPath);
  localStorage.setItem("historyPath", to.fullPath);
	const d = new Date().getTime(); //当前时间
  if(!l){
    // Toast('您还未登录,请先登录!');
  	// 第一次登录, 跳转到登录界面
   
    if(isWeiXin()){
      console.log("微信环境下自动登录")
      //如果是微信环境则自动登录
      let CropId = 'ww657bec0cb84a4e39'
      let agentId= '1000007'
      let agentSecret = 'UyIKaLsk2w2EmsG2z0HqyD5X2Lj6F7lN4cGEHSH7NeM'
      let redirect_uri = 'http%3a%2f%2fxgj.n3.cn%2fmobile%2f%23%2flogin';
      // let state = encodeUnicode(store.state.curUrl.fullPath || '/home');
      // console.log('初始化的state', state)
      let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${CropId}&redirect_uri=${redirect_uri}&scope=snsapi_base&response_type=code&agentid=${agentId}&state=123#wechat_redirect`;
      window.location.href=url;
    }else{
      router.push({ path: "/login" });
    }
  }else{
  	//存在token,判断token是否过期
    const diff = l.expireAt * 1000 - d;
    if (diff > 1000 * 60 * 60 * 24) {
      //还未失效
      store.dispatch("getAppInfo")
      next();
      return;
    } else {
      //token失效
      Toast('您的登录信息已失效,请重新登录!');
      localStorage.removeItem("loginInfo");
      router.push({ path: "/login" });
      next();
      return;
    }
  }
  next();
})

 new Vue({
  el: '#app',
  components: { App },
  template: '<App/>',
  // 为根组件加入路由
  router,
  store
})
